'use strict'

let { User } = require('../models');

let index_fn = async (ctx, next) => {
    ctx.render('index.html');
};
let login_fn = async (ctx, next) => {
    ctx.render('login.html');
};
let register_fn = async (ctx, next) => {
    ctx.render('register.html', { msg: '' });
};
let loginDone_fn = async (ctx, next) => {

};
let registerDone_fn = async (ctx, next) => {
    
    let uid = ctx.request.body.username.trim() || '';
    let pwd = ctx.request.body.password.trim() || '';
    let confirmpwd = ctx.request.body.confirmpassword.trim() || '';

    let res = '';

    if (uid.length > 0 && pwd.length > 0 && pwd === confirmpwd) {
        let row = await User.findOne({
            where: {
                username: uid
            }
        });
        let u2Json = JSON.stringify(row);
        console.log(u2Json);
        if (u2Json === 'null') {
            let u1 =await User.create({
                username: uid,
                password: pwd
            });
            let u1Json=JSON.stringify(u1);
            if(u1Json!=='null'){
                res = { code: 200, msg: '用户注册成功' };
            }else{
                res = { code: 1000, msg: '因为服务器或者网络原因，用户未注册成功' };
            }           
        } else {
            res = { code: 1000, msg: '当前用户名已经注册，请确认后重试' };
        }
    } else {
        res = { code: 1000, msg: '用户名和密码不能为空，且两密码应该一致' };
    }
    // 返回
    ctx.body = JSON.stringify(res);
};


module.exports = {
    '/': ['get', index_fn],
    '/login': ['get', login_fn],
    '/register': ['get', register_fn],
    '/loginDone': ['post', loginDone_fn],
    '/registerDone': ['post', registerDone_fn],
}